package gatewayservice.gatewayservice;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;


@Component
public class AuthFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数中的token

        ServerHttpRequest request = exchange.getRequest();

        String url = request.getPath().toString();

        if (url.contains("/login") || url.contains("/doc.html") || url.contains("/register")) {
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        System.out.println(token);
         //检查 token 是否为空
        if (token == null || token.isEmpty()) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        try {
            Claims claims = Jwts.parser()
                    .setSigningKey("micro")
                    .parseClaimsJws(token)
                    .getBody();

            System.out.println("over");

        }  catch (Exception e) {
            System.out.println("Invalid token: " + e.getMessage());
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        // 继续执行过滤器链
        return chain.filter(exchange);
    }


//        if(!token.equals("1")){
//            //响应http状态码（401）
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//            //请求结束
//            return exchange.getResponse().setComplete();
//        }
//        //继续执行过滤器链中的下一个资源
//        return chain.filter(exchange);
//    }
}
